<template>
  <div class="leftbar">
    <ul>
      <li :class="{ active: isActive('/home') }">发现音乐</li>
      <li>播客</li>
      <li>视频</li>
      <li>朋友</li>
      <li>直播</li>
      <li>私人FM</li>

      <li class="title">我的音乐</li>
      <li><img src="../../assets/img/音乐.png" alt="" />本地音乐</li>
      <li><img src="../../assets/img/下载.png" alt="" />下载管理</li>
      <li><img src="../../assets/img/历史播放.png" alt="" />最近播放</li>
      <li><img src="../../assets/img/云.png" alt="" />我的音乐云盘</li>
      <li><img src="../../assets/img/用户.png" alt="" />我的收藏</li>
    </ul>
    <div class="login">
      <el-button type="primary" @click="login" v-if="!hadlogin">登录</el-button>
      <el-button type="danger" @click="loginOut" v-else>退出</el-button>
      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
      >
        <h2>请扫描下方二维码登录</h2>
        <div class="item">
          <img :src="code" alt="" />
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
        </span>
      </el-dialog>
    </div>
    <div class="mygd" v-if="hadlogin">
      <el-collapse v-model="activeNames" @change="handleChange">
        <el-collapse-item title="我的歌单" name="1">
          <ul>
            <li
              v-for="i in gdlist"
              :key="i.id"
              class="gdlist"
              @click="togd(i.id)"
            >
              {{ i.name }}
            </li>
          </ul>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      code: "",
      dialogVisible: false,
      user: {},
      activeNames: ["1"],
      hadlogin: false,
      gdlist: [],
    };
  },
  methods: {
    setCookie(cname) {
      let date = new Date();
      date.setTime(date.getTime() - 10000);
      document.cookie = cname + "=a; expires=" + date.toGMTString();
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => {});
    },
    handleChange(val) {
      console.log(val);
    },
    initData() {
      this.$request({
        url: "/user/playlist",
        params: {
          uid: this.$store.state.userId,
        },
        withCredentials: true,
      }).then((success) => {
        if (success.data.code == 200) {
          this.hadlogin = true;
          console.log(success.data);
          this.gdlist = success.data.playlist;
        }
      });
    },
    togd(id) {
      this.$router.push({ name: "songlist", query: { id: id } });
      this.$root.eventhub.$emit("gddata");
    },
    async checkStatus(key) {
      const res = await this.$request({
        url: `/login/qr/check?key=${key}&timerstamp=${Date.now()}`,
        withCredentials: true, //关键
      });
      return res.data;
    },
    async getLoginStatus() {
      const res = await this.$request({
        url: `/login/status?timerstamp=${Date.now()}`,
        withCredentials: true, //关键
      });

      if (res.data.data.profile) {
        this.user = res.data.data.profile;
        localStorage.setItem("userId", this.user.userId);
        console.log(this.user);
      }
    },

    async login() {
      this.dialogVisible = true;
      let timer;
      const res = await this.$request({
        url: `/login/qr/key?timerstamp=${Date.now()}`,
        withCredentials: true, //关键
      });
      const key = res.data.data.unikey;
      const res2 = await this.$request({
        url: `/login/qr/create?key=${key}&qrimg=true&timerstamp=${Date.now()}`,
        withCredentials: true, //关键
      });
      this.code = res2.data.data.qrimg;

      timer = setInterval(async () => {
        const statusRes = await this.checkStatus(key);
        if (statusRes.code === 800) {
          alert("二维码已过期,请重新获取");
          clearInterval(timer);
        }
        if (statusRes.code === 803) {
          // 这一步会返回cookie
          clearInterval(timer);
          this.dialogVisible = false;
          alert("授权登录成功");
          await this.getLoginStatus();
          this.$root.eventhub.$emit("login_success");
          location.reload()
        }
      }, 3000);
    },
    loginOut() {
      this.$request({
        url: "/logout",
      }).then((success) => {
        console.log(success.data);
        this.setCookie("MUSIC_U");
        localStorage.setItem("userId", "");
        this.hadlogin = false;
      });
    },
  },
  computed: {
    isActive() {
      return function (path) {
        return this.$route.path.includes(path);
      };
    },
  },
  mounted() {
    this.initData();
  },
};
</script>

<style scoped>
img {
  vertical-align: middle;
  margin-right: 5px;
}
.leftbar {
  width: 200px;
  height: 1010px;
  padding-top: 10px;
  border-right: 1px solid #ccc;
}
li {
  padding: 0 10px;
  margin-left: 10px;
  height: 40px;
  line-height: 40px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  border-radius: 5px;
  font-size: 17px;
  margin-bottom: 2px;
}
li:hover {
  background-color: #f6f6f7;
}
.title {
  color: #999999;
  font-weight: 100;
}
.title:hover {
  background-color: white;
}
.active {
  font-weight: bold;
  font-size: 20px;
  background-color: #f6f6f7;
}
.login {
  text-align: center;
  margin-bottom: 20px;
}
h2 {
  margin-bottom: 20px;
}
.item {
  margin-bottom: 20px;
}
.gdlist {
  font-size: 14px;
  padding: 0 10px 0 0;
}
.el-collapse {
  padding-left: 20px;
}
</style>